#include "LibraryBuilder.h"
#include <iostream>
#include <taglib/fileref.h>
#include <taglib/tag.h>

LibraryBuilder::LibraryBuilder() {}

LibraryBuilder::~LibraryBuilder() {}

void LibraryBuilder::generateLibraryFile(std::string & libraryFile,
		std::string & root) {
	fileStream.open(libraryFile.c_str());
	if (root.at(root.length() - 1) == '/')
		root.erase(root.length() - 1, 1);
	recurseDirectory(root);
	fileStream.close();
}

void LibraryBuilder::processFile(std::string & path) {
	TagLib::FileRef file(path.c_str());
	if (!file.isNull()) {
		TagLib::String artistName = file.tag()->artist();
		TagLib::String albumTitle = file.tag()->album();
		TagLib::String songTitle = file.tag()->title();
		TagLib::String genre = file.tag()->genre();
		TagLib::uint year = file.tag()->year();
		TagLib::uint trackNumber = file.tag()->track();
		TagLib::uint length = file.audioProperties()->length();
		TagLib::uint bitrate = file.audioProperties()->bitrate();
		fileStream << artistName << SEPARATOR
		           << albumTitle << SEPARATOR
		           << songTitle << SEPARATOR
		           << genre << SEPARATOR
		           << year << SEPARATOR
		           << trackNumber << SEPARATOR
		           << length << SEPARATOR
		           << bitrate << SEPARATOR
		           << path << std::endl;
	}
}

void LibraryBuilder::recurseDirectory(std::string & path) {
	DIR * dir;
	struct dirent * ent;
	dir = Opendir(path.c_str());
	while ((ent = Readdir(dir))) {
		std::string temp(ent->d_name);
		if (temp == "." || temp == "..")
			continue;

		std::string fileName(path);
		fileName += "/" + temp;
		struct stat buf;
		Stat(fileName.c_str(), &buf);
		if (S_ISDIR(buf.st_mode))
			recurseDirectory(fileName);
		else if (S_ISREG(buf.st_mode))
			processFile(fileName);
	}
	Closedir(dir);
}
